package com.blankii.androidlibrary.utils

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Environment
import com.blankii.androidlibrary.utils.HardwareInfoUtil.getAndroidId
import com.scottyab.aescrypt.AESCrypt
import java.io.File
import java.io.UnsupportedEncodingException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.text.SimpleDateFormat
import java.util.Date


object RWUtil {
    const val AES_KEY = "password"
    private const val MD5TAG = "blankii" //与加密文本一块加密
    private const val APP_FILE_NAME = ".app.txt"

    fun getBasePath(): String = Environment.getExternalStorageDirectory().absolutePath + "/"

    fun getAppFile(): File = getFile(APP_FILE_NAME)

    private fun getFile(fileName: String): File = File(getBasePath(), fileName)

    data class AppTxtBean(val appId: String, val useTimeMax: String, val lastUseTime: String) {

    }

    fun writeFileByLines(file: File, appTxtBean: AppTxtBean) {
        var result = "${appTxtBean.appId}\r\n${appTxtBean.useTimeMax}\r\n${appTxtBean.lastUseTime}"
        file.writeText(result)
    }

    fun readFileByLines(file: File): AppTxtBean {
        val linesArray = file.readLines()
        return AppTxtBean(linesArray[0], linesArray[1], linesArray[2])
    }

    fun getUseTimeMax(): String {
        return "20260000000000"
    }

    /**
     * 获取当前app version name
     * 只是展示给用户看的
     * versionCode 才是应用市场，应用升级安装时的重点
     * 高版本的versionCode 才能在低版本的versionCode 软件设备上正常安装
     */
    fun getAppVersionName(context: Context): String? {
        var appVersionName = ""
        try {
            val packageInfo: PackageInfo =
                context.applicationContext.packageManager.getPackageInfo(context.packageName, 0)
            appVersionName = packageInfo.versionName
        } catch (e: PackageManager.NameNotFoundException) {
            throw e
        }
        return appVersionName
    }

    /**
     * 获取当前时间格式
     */
    fun getTime(): String {
        return SimpleDateFormat("yyyyMMddHHmmss").format(Date(System.currentTimeMillis()))
    }

    //androidId:b81237cf4f7a9e73,md5:99d40693ff3430f1e9a7a3daea9281d5
    fun createMD5(context: Context): String = md5("$MD5TAG${getAndroidId()}")

    //yyyyMMddHHmmss  共14位
    fun getValidTimeLength(): Int {
        return "20260000000000".length
    }

    /**
     * 检查数据格式长度是否合法
     */
    fun checkDataValid(context: Context, appTxtBean: AppTxtBean): Boolean {
        return !(appTxtBean.appId != getAndroidId() || appTxtBean.useTimeMax.length != getValidTimeLength() || appTxtBean.lastUseTime.length != getValidTimeLength())
    }

    fun md5(value: String): String {
        var result: String? = null
        var md5: MessageDigest? = null
        try {
            md5 = MessageDigest.getInstance("MD5")
            md5.update(value.toByteArray(charset("UTF-8")))
        } catch (error: NoSuchAlgorithmException) {
            error.printStackTrace()
        } catch (e: UnsupportedEncodingException) {
            e.printStackTrace()
        }
        val b = md5!!.digest()
        var i: Int
        val buf = StringBuffer("")
        for (offset in b.indices) {
            i = b[offset].toInt()
            if (i < 0) {
                i += 256
            }
            if (i < 16) {
                buf.append("0")
            }
            buf.append(Integer.toHexString(i))
        }
        result = buf.toString()
        return result
    }

    /**
     * 复制string到剪切板
     */
    fun String.strToClip(context: Context) {
        val manager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        val clipData = ClipData.newPlainText("label", this)
        manager.setPrimaryClip(clipData)
    }

    /**
     * 剪切版转字符串
     */
    fun getClipData(context: Context): String {
        val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        val clipData = cm.primaryClip
        return clipData?.getItemAt(0)?.text.toString()
    }

    /**
     * 使用app_id 后四位作为秘钥
     */
    fun enAESByKey(trailStr: String, data: String): String {
        return AESCrypt.encrypt(trailStr, data)
    }


    /**
     * 使用app_id 后四位作为秘钥
     */
    fun deAESByKey(trailStr: String, data: String): String {
        return AESCrypt.decrypt(trailStr, data)
    }

    fun getAndroidIdLastStr(): String {
        val androidId = getAndroidId()
        return androidId.substring(androidId.length - 4)
    }
}